/*
 * frame.c
 *
 *  Created on: 2012-05-05
 *      Author: Rafal Sokolowski
 */

#include "board.h"
#include "frame.h"
#include "tmry.h"
#include "ledy.h"

void frameTranslate ( void ){

	if (g_oIncomingFrame.u16_MsgIsFresh)
	{
		g_oIncomingFrame.u8_Addr = (g_oIncomingFrame.i32_MsgRaw & 0xC0) >> 6;
		g_oIncomingFrame.u8_Start = (g_oIncomingFrame.i32_MsgRaw & 0x20) >> 5;
		g_oIncomingFrame.u8_Dir = (g_oIncomingFrame.i32_MsgRaw & 0x18) >> 3;
		g_oIncomingFrame.u8_Speed = (g_oIncomingFrame.i32_MsgRaw & 0x03);

		if (!g_oIncomingFrame.u8_Addr || 3 == g_oIncomingFrame.u8_Addr)
		{
			g_oLedSetting.u8_Start = g_oIncomingFrame.u8_Start;
			g_oLedSetting.u8_Dir = g_oIncomingFrame.u8_Dir;
            g_oLedSetting.u8_Speed = g_oIncomingFrame.u8_Speed;
		}
		if (g_oIncomingFrame.u8_Addr) frameRelay();
		g_oIncomingFrame.u16_MsgIsFresh = 0;
	}
}

int changeSM( void ){
	g_oFlags.u8_MasterSlave ^= 0x01;
	(g_oFlags.u8_MasterSlave) ?  timerStop(g_i32Led_timerID) : timerStart(g_i32Led_timerID, 100);

	g_oFlags.u8_3secondPassed = 1;
	// TODO led czerwony toggle;
	gpio_tgl_gpio_pin(LED6_GPIO);

}

void frameSend (void)
{
    if (g_oOutcomingFrame.u16_MsgIsReadyToGo)
    {
    	usart_write_char((&AVR32_USART1), g_oOutcomingFrame.i32_MsgRaw);
    	g_oOutcomingFrame.u16_MsgIsReadyToGo = 0;
    }
}

void frameRelay (void)
{
	if (3 == g_oIncomingFrame.u8_Addr)
	{
		g_oOutcomingFrame.i32_MsgRaw = g_oIncomingFrame.i32_MsgRaw;
		g_oOutcomingFrame.u16_MsgIsReadyToGo = 1;
		frameSend();
	}
	else if (g_oIncomingFrame.u8_Addr)
	{
		g_oOutcomingFrame.i32_MsgRaw = g_oIncomingFrame.i32_MsgRaw & 0x3F;
		g_oOutcomingFrame.i32_MsgRaw |= (g_oIncomingFrame.u8_Addr-1) << 6;
		g_oOutcomingFrame.u16_MsgIsReadyToGo = 1;
		frameSend();
	}
}

void framePrepare (void)
{
	g_oOutcomingFrame.i32_MsgRaw = (g_oOutcomingFrame.u8_Addr << 6) + (g_oOutcomingFrame.u8_Start << 5) + (g_oOutcomingFrame.u8_Dir << 3) + (g_oOutcomingFrame.u8_Speed);
	g_oOutcomingFrame.u8_Addr = g_oOutcomingFrame.u8_Start = g_oOutcomingFrame.u8_Dir = g_oOutcomingFrame.u8_Speed = 0;
	g_oOutcomingFrame.u16_MsgIsReadyToGo = 1;
	frameSend();
}
